package models

import (
	"fmt"

	"github.com/jinzhu/gorm"
	db "hais.pw/shorturl/database"
)

type Link struct {
	gorm.Model
	Address string `gorm:"not null;"` // 设置字段为非空并唯一,原始地址
	NewUrl  string //新的地址
	Short   string `gorm:"type:varchar(6);not null;unique"`
	Click   uint
}

func (link *Link) Add() (err error) {
	err = db.Exectue.Create(&link).Error
	if err == nil && link.Short == "" {
		link.Short = fmt.Sprintf("T%d", link.ID)
		err = link.Save()
	}
	return err
}

func (link *Link) FindById() (err error) {
	err = db.Exectue.First(&link, link.ID).Error
	return err
}

func (link *Link) FindByShort() (err error) {
	err = db.Exectue.Where("short = ?", link.Short).First(&link).Error
	return err
}

func (link *Link) Save() (err error) {
	err = db.Exectue.Save(&link).Error
	return err
}
